package site.edody.dframe.rocketmq;


import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ProducerService {
    private final Logger logger = LoggerFactory.getLogger(ProducerService.class);

    @Autowired
    private Map<String, DefaultMQProducer> producers;

    public SendResult sendMessage(String producerName, String topic, String tag, String message) {
        DefaultMQProducer producer = producers.get(producerName);
        if (producer == null) {
            throw new IllegalArgumentException("Producer not found: " + producerName);
        }

        try {

            Message msg = new Message(topic, tag, message.getBytes());
            SendResult result = producer.send(msg, 3000); // 指定超时时间
            return producer.send(msg);
        } catch (MQClientException e) {
            logger.error("客户端配置错误", e);
        } catch (RemotingException e) {
            logger.error("网络通信异常", e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("发送被中断", e);
        } catch (MQBrokerException e) {
            logger.error("Broker处理错误: {}", e.getErrorMessage(), e);
        } catch (Exception e){
            logger.error("其他异常: {}",e.getMessage(), e);
        }
        throw new RuntimeException("消息发送失败");
    }
}